package com.bj58.groupbuy.action.threads;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import com.bj58.groupbuy.action.model.UserSubMailVo;
import com.bj58.groupbuy.action.service.UserSubMailService;
import com.bj58.groupbuy.service.locator.ServiceLocator;

public class UserSubMonitorThread extends Thread{

	@SuppressWarnings("static-access")
	public void run(){
		try {
			
			while(true)
			{
			
				UserSubMailService UserSubMailService = ServiceLocator.get(UserSubMailService.class);
				List<UserSubMailVo> smList = UserSubMailService.getAllToSendList();//所有状态正常的订阅
				List<UserSubMailVo> sendList = new ArrayList<UserSubMailVo>(); //待发送的订阅  
				if(null!=smList&&smList.size()>0)
				{
					for(UserSubMailVo vo : smList){
						//如果vo正在执行，即还没执行完，则延长5分钟后再次尝试添加
						String modTime = vo.getModTime();
						if("".equals(modTime)  || null == modTime)//vo.getId()%3==0&&
						{
							sendList.add(vo);
						}
					}
				}
				
				if(null == sendList || sendList.isEmpty()){
					
					System.out.println("Monitor:No thread have to run !");
					this.sleep(5*1000);//5s扫描一次
				}else{
					int corePoolSize = Runtime.getRuntime().availableProcessors();//CPU个数
					long keepAliveTime = 10; //线程活动保持时间
					LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(sendList.size()); //线程队列
					ThreadPoolExecutor  pool = new ThreadPoolExecutor(1, corePoolSize/2, keepAliveTime, TimeUnit.SECONDS, queue);
					UserDownfileThread.threadDoneCount=new AtomicInteger();
					for(UserSubMailVo vo : sendList){
						Thread  thread = new UserDownfileThread(vo);
						pool.submit(thread);
						vo.setState(3);
					}
					while(true)
					{
						
						if(UserDownfileThread.threadDoneCount.get() == sendList.size()){
								pool.shutdown();
								System.out.println("This sub mail has done!");
								break;
						}
					}
					this.sleep(5*1000);//5s扫描一次
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public static void main(String[] args) {
		try {
			
			UserSubMonitorThread  thread = new UserSubMonitorThread();
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}
}
